package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author ${xinpl}
 * @Description 权限接口服务实现类
 */
@Service(interfaceClass = PermissionService.class)
@Transactional
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;


    /**
    *@author ${xinpl}
    *@Description 权限数据分页展示
    *@Date 2020/4/16 11:22
    *@Param [pageBean]
    *@return com.itheima.constant.PageResult
    **/
    @Override
    public PageResult findPage(QueryPageBean pageBean) throws Exception{
        PageHelper.startPage(pageBean.getCurrentPage(),pageBean.getPageSize());
        Page<Permission> page = permissionDao.selectByCondition(pageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
    *@author ${xinpl}
    *@Description 新增权限
    *@Date 2020/4/15 21:57
    *@Param [permission]
    *@return void
    **/
    @Override
    public void add(Permission permission) throws Exception{
        permissionDao.insertSelective(permission);
    }

    /**
    *@author ${xinpl}
    *@Description 权限删除
    *@Date 2020/4/16 11:22
    *@Param [id]
    *@return void
    **/
    @Override
    public void delete(int id) throws Exception{
        // 1.查询权限和角色是否存在关系
        int count = permissionDao.findCountByPermissionId(id);
        // 2.如果有关系则不允许删除
        if (count > 0) {
            throw new RuntimeException("id被外键引用,不能删除!");
        }
        // 3.如果没有关系可以删除
        permissionDao.deleteByPrimaryKey(id);
    }

    /**
    *@author ${xinpl}
    *@Description 根据权限id 回显数据
    *@Date 2020/4/16 11:22
    *@Param [id]
    *@return com.itheima.pojo.Permission
    **/
    @Override
    public Permission findById(int id) throws Exception{
        return permissionDao.selectByPrimaryKey(id);
    }

    /**
    *@author ${xinpl}
    *@Description 修改权限
    *@Date 2020/4/16 11:23
    *@Param [permission]
    *@return void
    **/
    @Override
    public void update(Permission permission) throws Exception{
        permissionDao.updateByPrimaryKeySelective(permission);
    }

    /**
    *@author ${xinpl}
    *@Description 校验权限是否已经存在
    *@Date 2020/4/16 11:23
    *@Param [name] 权限名 或 编号
    *@return java.lang.Boolean true:已存在
    **/
    public Boolean checkPermissionExist(String name)throws Exception{
        int count = permissionDao.checkPermissionExist(name);
        return count > 0;
    }
}
